/****************
 *@description:  售后订单列表   storeBackManage/orderManage/mallOrder
 *@author: Xhd
 *@API: 贺义龙
 *@date: 2023-11-13 09:44:38
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from "react";
import { Tabs, Modal } from "antd";
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from "@/components/TheButton";
import TheTable from '@/components/TheTable';
import ThePagination from "@/components/ThePagination";
import { apiShopSalesReturnPage, apiStoreInfoList, apiGetShopOrderInfoList } from '@/request/orderManagement';
import store from "@/store/store";
import _ from 'lodash';
import { getDateTime3 } from '@/utils/getDate';
import { exportSheetTable } from '@/utils/exportTable.js'

const { TabPane } = Tabs

class StoreBackAfterSaleOrder extends Component {
  constructor(props) {
    super(props)
    this.queryFormRef = React.createRef()
    this.state = {
      searchOption: [
        { field: 'returnCode', label: '订单/售后单编号', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'time', label: '申请时间', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
        { field: 'moneyStatus', label: '退款类型', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{ label: '全部', value: '', }, { label: '仅退款', value: 'N' }, { label: '退货退款', value: 'Y' }], defaultValue: '' },
        { field: 'memberId', label: '用户ID', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'memberPhone', label: '收货手机号', placeholder: '请输入', required: false, rules: [], type: 'Input', options: [], defaultValue: '' },
        { field: 'storeId', label: '所属商家', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [], txt: 'storeName', value: 'storeId', api: apiStoreInfoList, params: {}, },
        { field: 'goodsQuery', label: '商品ID/名称', placeholder: '支持模糊查询', required: false, rules: [], type: 'Input', defaultValue: '' },
      ],
      queryForm: {},
      tabData: [
        { key: "", tab: '全部' },
        { key: "1", tab: '退款中' },
        { key: "9", tab: '退款成功' },
        { key: "4", tab: '退款失败' },
        { key: "7", tab: '退款取消' },
        { key: "0", tab: '退款关闭' },
      ],
      salesStatus: "",
      columns: [
        {
          title: '订单编号',
          dataIndex: 'orderCode',
          key: 'orderCode',
        },
        {
          title: '售后单编号',
          dataIndex: 'returnCode',
          key: 'returnCode',
        },
        {
          title: '买家昵称',
          dataIndex: 'nickName',
          key: 'nickName',
        },
        {
          title: '退款商品',
          dataIndex: 'goodsName',
          key: 'goodsName',
          render: (text, record) => {
            let goodsSku = JSON.parse(record.goodsSkuJson)
            let arr = _.toArray(_.toArray(goodsSku).skuAttribute).map((v) => {
              return v.value
            })
            return (
              <div>
                <div>{text}</div>
                <div>{arr}</div>
              </div>
            )
          },
        },
        {
          title: '商家名称',
          dataIndex: 'storeName',
          key: 'storeName',
        },
        {
          title: '退款类型',
          dataIndex: 'moneyStatus',
          key: 'moneyStatus',
          render: (text, record) => {
            let label = ''
            switch (text) {
              case 'N':
                label = '仅退款'
                break
              case 'Y':
                label = '退货退款'
                break
            }
            return label
          },
        },
        {
          title: '实付金额（元）',
          dataIndex: 'detailPayPrice',
          key: 'detailPayPrice',
          render: (text, record) => {
            return <React.$Price price={text} />
          },
        },
        {
          title: '退款金额（元）',
          dataIndex: 'detailPayPrice',
          key: 'detailPayPrice',
          render: (text, record) => {
            return <React.$Price price={text} />
          },
        },
        {
          title: '申请时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
        {
          title: '退款状态',
          dataIndex: 'salesStatus',
          key: 'salesStatus',
          render: (text, record) => {
            let label = ''
            switch (parseInt(text)) {
              case 1:
                label = '退款中'
                break
              case 2:
                label = '退款中，平台已同意，待寄回商品'
                break
              case 3:
                label = '退款中，商品已寄回，待平台确认'
                break
              case 4:
                label = '退款失败'
                break
              case 5:
                label = '买家退货超时自动关闭'
                break
              case 6:
                label = '卖家拒收'
                break
              case 7:
                label = '用户取消退款'
                break
              case 9:
                label = '退款成功'
                break
              case 0:
                label = '退款关闭'
                break
            }
            return label
          },
        },
        {
          title: '操作',
          key: "",
          fixed: "right",
          render: (text, record) => {
            return <TheButton  haspermi={['storeBack:afterSale:detail']} type="link" onClick={() => this.toDetail(record.shopSalesReturnId)} >查看订单</TheButton>
          }
        },
      ],
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0
    }
  }

  componentDidMount() {
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'afterSale') {
      let { pageNo, pageSize, salesStatus } = searchParams
      this.setState({
        salesStatus,
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.queryFormRef.onSetDefault({ ...queryForm })
        this.getData(queryForm)
      })
    } else {
      this.getData()
    }
  }
  //获取数据
  getData = async (values) => {
    const { queryForm, salesStatus, pageData } = this.state
    if (values && !_.isEmpty(values.time)) {
      values.createTimeStart = getDateTime3(values.time[0]) + " 00:00:00"
      values.createTimeEnd = getDateTime3(values.time[1]) + " 23:59:59"
      delete (values.time)
    }
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      const params = {
        ...pageData, salesStatus, queryForm: this.state.queryForm
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'afterSale',
          ...params
        }
      })
      let res = await apiShopSalesReturnPage({ salesStatus, ...params.queryForm, ...pageData })
      if (res.code === 0 && res.data) {
        this.setState({
          dataSource: res.data,
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount
        })
      }
    })
  }
  // 详情
  toDetail = (id) => {
    this.props.history.push(`/storeBackManage/orderManage/afterSaleOrder/detail/${id}`)
  }
  //搜索
  onFormSearch = (values) => {
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 }
    }, () => {
      this.getData(values)
    })
  }
  //重置
  onReset = () => {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  //tab切换
  changeKey = (key) => {
    this.setState({
      salesStatus: key
    }, () => {
      this.getData()
    })
  }
  //翻页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: { pageNo, pageSize }
    }, () => {
      this.getData()
    })
  }
  //导出
  toExport = async () => {
    const { queryForm, salesStatus } = this.state
    if (!queryForm || Object.keys(queryForm).length === 0) {
      Modal.warning({
        title: "提醒",
        content: "请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。",
        okText: "我知道了",
        onOk: () => { }
      })
      return
    }
    let res = await apiShopSalesReturnPage({ ...queryForm, salesStatus, pageNo: 1, pageSize: 100, type: "Y", })
    if (res.code === 0 && res.data) {
      console.log(res.data);
      const th_arr = [
        {
          title: '售后订单列表',
          prop: '',
          children: [
            {
              title: '订单编号',
              prop: 'orderCode',
            },
            {
              title: '退单编号',
              prop: 'returnCode',
            },
            {
              title: '买家昵称',
              prop: 'nickName',
            },
            {
              title: '退款商品',
              prop: 'goodsName',
            },
            {
              title: '商家名称',
              prop: 'storeName',
            },
            {
              title: '退款类型',
              prop: 'moneyStatus',
            },
            {
              title: '订单金额（元）',
              prop: 'orderPrice',
              valueType: 'number'
            },
            {
              title: '实付金额（元）',
              prop: 'detailPayPrice',
              valueType: 'number'
            },
            {
              title: '退款金额（元）',
              prop: 'detailPayPrice',
              valueType: 'number'
            },
            {
              title: '申请时间',
              prop: 'createTime',
            },
            {
              title: '退款状态',
              prop: 'salesStatus',
            },
          ]
        },

      ]
      let tb_arr = []
      res.data.forEach(item => {
        tb_arr.push({
          orderCode: item.orderCode || '/',
          returnCode: item.returnCode || '/',
          nickName: item.nickName || '/',
          goodsName: item.goodsName || '/',
          storeName: item.storeName || '/',
          moneyStatus: item.moneyStatus === "N" ? "仅退款" : "退货退款",
          orderPrice: Number(item.orderPrice / 100).toFixed(2) || '/',
          detailPayPrice: Number(item.detailPayPrice / 100).toFixed(2) || '/',
          detailPayPrice: Number(item.detailPayPrice / 100).toFixed(2) || '/',
          createTime: item.createTime || '/',
          salesStatus: item.salesStatus === '1' ? "退款中" : item.salesStatus === '4' ? "退款失败" : item.salesStatus === '9' ? "退款成功" : item.salesStatus === '0' ? "退款关闭" : ""
        })
      })
      exportSheetTable({ fileName: `售后订单${salesStatus === '1' ? "退款中" : salesStatus === '4' ? "退款失败" : salesStatus === '9' ? "退款成功" : salesStatus === '0' ? "退款关闭" : ""}`, tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false, })
    }
  }

  render() {
    const { searchOption, tabData, columns, dataSource, pageData, total } = this.state
    return (
      <div className='p-layout-box'>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={true} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
          <TheButton haspermi={['storeBack:afterSale:export']} size="middle" onClick={() => this.toExport()} type="default">导出</TheButton>
        </TheQueryForm>
        <Tabs onChange={this.changeKey} >
          {tabData.map(v => {
            return <TabPane key={v.key} tab={v.tab}>
              <TheTable
                columns={columns}
                dataSource={dataSource}
              ></TheTable>
              <ThePagination
                pageNo={pageData.pageNo}
                pageSize={pageData.pageSize}
                total={total}
                pageChange={this.pageChange}
              ></ThePagination>
            </TabPane>
          })}
        </Tabs>
      </div>
    )
  }

}

export default StoreBackAfterSaleOrder